package com.cooldatasoft.taskManager.component;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import com.cooldatasoft.domain.model.Event;
import com.cooldatasoft.domain.model.Project;
import com.cooldatasoft.domain.model.User;
import com.cooldatasoft.domain.model.UserProjectRoles;
import com.cooldatasoft.domain.service.EventService;
import com.cooldatasoft.domain.service.UserProjectRolesService;
import com.cooldatasoft.security.TaskManagerSecurityManager;
import com.vaadin.addon.calendar.event.BasicEvent;
import com.vaadin.addon.calendar.event.CalendarEvent;
import com.vaadin.addon.calendar.event.CalendarEventProvider;

@Configurable(preConstruction = true)
public class MyEventProvider implements CalendarEventProvider {

	@Autowired
	private EventService eventService;

	@Autowired
	private UserProjectRolesService userProjectRolesService;

	@Autowired
	private TaskManagerSecurityManager securityManager;

	List<CalendarEvent> events;

	public MyEventProvider() {
		events = new ArrayList<CalendarEvent>();
		
		User currentUser = securityManager.getCurrentUser();
		List<Event> eventsFromDB = eventService.getAllEventOfUser(currentUser);
		List<UserProjectRoles> uprByUserFromDB = userProjectRolesService
				.getUserProjectRolesByIdUser(securityManager.getCurrentUser());

		MyCalendarEvent e0;
		for (Event e : eventsFromDB) {
			e0 = new MyCalendarEvent();
			e0.setIdent(e.getIdEvent());
			e0.setCaption(e.getCaption());
			e0.setDescription(e.getDescription());
			e0.setStart(e.getStart());
			e0.setEnd(e.getEnd());
			e0.setStyleName(e.getStyleName());
			e0.setAllDay(e.isAll_day());
			e0.setUser(e.getIdUser());
			events.add(e0);
		}

		Project project;
		Set<Long> projectIDs = new HashSet<Long>();
		for (UserProjectRoles upr : uprByUserFromDB) {
			project = upr.getIdProject();
			boolean bool = projectIDs.add(project.getIdProject());
			if(bool) {
				e0 = new MyCalendarEvent();
				e0.setIdent(0);
				e0.setCaption(project.getName());
				e0.setDescription(project.getDescription());
				e0.setStart(project.getCreated());
				e0.setEnd(project.getFinished());
				e0.setStyleName("project");
				e0.setAllDay(true);
				e0.setUser(currentUser);
				events.add(e0);
			}
		}
	}

	public List<CalendarEvent> getEvents(Date startDate, Date endDate) {
		return events;
	}

	public void removeEvent(MyCalendarEvent myCalendarEvent) {
		events.remove(myCalendarEvent);
	}

	public void addEvent(MyCalendarEvent myCalendarEvent) {
		events.add(myCalendarEvent);
	}

}